package com.ebrothers.isns.controller;

import java.util.List;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.ebrothers.isns.R;
import com.ebrothers.isns.map.NetworkLocator;
import com.ebrothers.isns.map.NetworkLocator.OnLocatedListener;
import com.ebrothers.isns.map.ovarlay.MyLocationOverlay;
import com.ebrothers.isns.util.Utils;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class MapViewController extends ViewController {

	private MapController mMapController;
	private NetworkLocator mLocator;
	private MapView mMapView;
	private MyLocationOverlay mMyLocationOverlay;

	public MapViewController(Context context, View view) {
		super(context, view);
	}

	@Override
	public void onViewBinded(View view) {
		mMapView = (MapView) view;
		mMapView.setBuiltInZoomControls(true);
		mMapView.setSatellite(true);
		mMapView.setStreetView(true);
		List<Overlay> overlays = mMapView.getOverlays();
		final Context context = getContext();
		mMyLocationOverlay = new MyLocationOverlay(context);
		overlays.add(mMyLocationOverlay);
		mMapController = mMapView.getController();
		mLocator = new NetworkLocator(context);
		mLocator.setOnLocatedListener(new OnLocatedListener() {
			public void onLocated(Location location) {
				animateToMyLocation(location);
			}

			public void onLocateFaild() {
				Toast.makeText(context,
						context.getText(R.string.msg_need_network),
						Toast.LENGTH_SHORT).show();
			}
		});
		mLocator.locate();
	}

	private void animateToMyLocation(Location location) {
		final GeoPoint point = Utils.locationToGeoPoint(location);
		mMyLocationOverlay.moveTo(point);
		mMapController.setZoom(16);
		mMapController.animateTo(point);
		mMapView.invalidate();
	}

	@Override
	public void onViewSelected(Bundle data) {
		mLocator.locate();
	}

}
